﻿using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using XSerialPort;

namespace XChip_I2C_SerialPort
{
    /// <summary>
    /// CheckBox绑定数据模型
    /// </summary>
    public class CheckBoxItem
    {
        public string Name { get; set; }
        public bool IsChecked { get; set; }
    }

    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window, INotifyPropertyChanged
    {
        #region 私有字段
        private bool _isUsbOpen = false;
        private bool _isUsbI2cOpen = false;
        private CancellationTokenSource _cancellationTokenSource;
        private uint _i2cUsbIndex = 0;       // 打开的USB-I2C设备序号
        #endregion

        #region 绑定属性（INotifyPropertyChanged）
        private ObservableCollection<USBDeviceModel> _i2cPortList;
        public ObservableCollection<USBDeviceModel> I2CPortList
        {
            get => _i2cPortList;
            set
            {
                _i2cPortList = value;
                OnPropertyChanged();
            }
        }

        private ObservableCollection<string> _i2cUsbPortList;
        public ObservableCollection<string> I2CUsbPortList
        {
            get => _i2cUsbPortList;
            set
            {
                _i2cUsbPortList = value;
                OnPropertyChanged();
            }
        }

        private USBDeviceModel _selectedI2CPort;
        public USBDeviceModel SelectedI2CPort
        {
            get => _selectedI2CPort;
            set
            {
                _selectedI2CPort = value;
                OnPropertyChanged();
            }
        }

        private string _selectedI2CUsbPort;
        public string SelectedI2CUsbPort
        {
            get => _selectedI2CUsbPort;
            set
            {
                _selectedI2CUsbPort = value;
                OnPropertyChanged();
            }
        }

        public bool IsUsbOpen
        {
            get => _isUsbOpen;
            set
            {
                _isUsbOpen = value;
                OnPropertyChanged();
                UpdateStatusText();
            }
        }

        public bool IsUsbI2cOpen
        {
            get => _isUsbI2cOpen;
            set
            {
                _isUsbI2cOpen = value;
                OnPropertyChanged();
                UpdateStatusText();
            }
        }

        // A/B组CheckBox绑定集合
        public ObservableCollection<CheckBoxItem> AGroupItems { get; set; }
        public ObservableCollection<CheckBoxItem> BGroupItems { get; set; }


        // 属性定义
        public ObservableCollection<string> RegisterPortList { get; set; }
        public ObservableCollection<int> BaudRateList { get; set; }
        public ObservableCollection<int> DataBitsList { get; set; }

        private string _selectedRegisterPort;
        public string SelectedRegisterPort
        {
            get => _selectedRegisterPort;
            set  { _selectedRegisterPort = value; OnPropertyChanged(); }
        }

        private int _selectedBaudRate;
        public int SelectedBaudRate
        {
            get => _selectedBaudRate;
            set { _selectedBaudRate = value; OnPropertyChanged(); }
        }

        private int _selectedDataBits;
        public int SelectedDataBits
        {
            get => _selectedDataBits;
            set { _selectedDataBits = value; OnPropertyChanged(); }
        }
        private string _registerButtonText;
        public string RegisterButtonText
        {
            get => _registerButtonText;
            set { _registerButtonText = value; OnPropertyChanged(); }
        }
        private Brush _registerButtonColor;
        public Brush RegisterButtonColor
        {
            get => _registerButtonColor;
            set { _registerButtonColor = value; OnPropertyChanged(); }
        }
        #endregion

        #region 构造函数
        public MainWindow()
        {
            InitializeComponent();
            DataContext = this;

            // 初始化设备列表
            I2CPortList = new ObservableCollection<USBDeviceModel>();
            I2CUsbPortList = new ObservableCollection<string>();

            // 初始化A/B组CheckBox（a1-a40、b1-b40）
            AGroupItems = new ObservableCollection<CheckBoxItem>();
            BGroupItems = new ObservableCollection<CheckBoxItem>();
            for (int i = 1; i <= 40; i++)
            {
                AGroupItems.Add(new CheckBoxItem { Name = $"a{i}" });
                BGroupItems.Add(new CheckBoxItem { Name = $"b{i}" });
            }

            // 初始状态：禁用停止按钮
            TestStartEnd.IsEnabled = false;

            // 刷新设备列表
            RefreshI2CPorts();
            //RefreshI2CUsbPorts();
            RegisterPortList = new ObservableCollection<string>();
            BaudRateList = new ObservableCollection<int> { 9600, 19200, 38400, 57600, 115200 };
            DataBitsList = new ObservableCollection<int> { 5, 6, 7, 8 };
      
            SelectedBaudRate = 115200;
            SelectedDataBits = 8;
            RegisterButtonText = "打开";
            RegisterButtonColor = Brushes.LimeGreen;
        }
        #endregion

        #region 测试相关变量（修正拼写错误、规范命名）
        private bool?[] _testEnCheckboxStates = new bool?[80];    // 测试使能CheckBox状态
        private bool?[] _testResultTemp = new bool?[80];         // 临时测试结果
        private bool?[] _testResultFinal = new bool?[80];        // 最终测试结果（原TestRuslutFinal拼写错误）

        // 测试每个通道时需写入80500208寄存器的值（格式对齐优化）
        private readonly int[] _loopTestValue = {
            0x00008600, 0x00008601, 0x00008602, 0x00008603, 0x00008604, 0x00008605, 0x00008606, 0x00008607,
            0x00008608, 0x00008609, 0x0000860A, 0x0000860B, 0x0000860C, 0x0000860D, 0x0000860E, 0x0000860F,
            0x00008500, 0x00008501, 0x00008502, 0x00008503, 0x00008504, 0x00008505, 0x00008506, 0x00008507,
            0x00008508, 0x00008509, 0x0000850A, 0x0000850B, 0x0000850C, 0x0000850D, 0x0000850E, 0x0000850F,
            0x00008300, 0x00008301, 0x00008302, 0x00008303, 0x00008304, 0x00008305, 0x00008306, 0x00008307,
            0x00004600, 0x00004601, 0x00004602, 0x00004603, 0x00004604, 0x00004605, 0x00004606, 0x00004607,
            0x00004608, 0x00004609, 0x0000460A, 0x0000460B, 0x0000460C, 0x0000460D, 0x0000460E, 0x0000460F,
            0x00004500, 0x00004501, 0x00004502, 0x00004503, 0x00004504, 0x00004505, 0x00004506, 0x00004507,
            0x00004508, 0x00004509, 0x0000450A, 0x0000450B, 0x0000450C, 0x0000450D, 0x0000450E, 0x0000450F,
            0x00004300, 0x00004301, 0x00004302, 0x00004303, 0x00004304, 0x00004305, 0x00004306, 0x00004307
        };
        #endregion

        #region CheckBox操作方法（抽取为独立区域，优化可读性）
        /// <summary>
        /// 保存所有CheckBox的选中状态
        /// </summary>
        private void SaveCheckBoxStates()
        {
            CheckBox[] checkBoxes = GetCheckBoxArray();
            for (int i = 0; i < checkBoxes.Length; i++)
            {
                _testEnCheckboxStates[i] = checkBoxes[i].IsChecked;
            }
        }

        /// <summary>
        /// 从数组恢复所有CheckBox的选中状态
        /// </summary>
        private void LoadCheckBoxStates()
        {
            CheckBox[] checkBoxes = GetCheckBoxArray();
            for (int i = 0; i < checkBoxes.Length; i++)
            {
                checkBoxes[i].IsChecked = _testEnCheckboxStates[i];
            }
            MessageBox.Show("所有CheckBox状态已从数组恢复!", "恢复成功", MessageBoxButton.OK, MessageBoxImage.Information);
        }

        /// <summary>
        /// 取消所有CheckBox的选中状态
        /// </summary>
        private void ClearAllCheckBoxes()
        {
            foreach (var cb in GetCheckBoxArray())
            {
                cb.IsChecked = false;
            }
        }

        /// <summary>
        /// 选中所有CheckBox
        /// </summary>
        private void SelectAllCheckBoxes()
        {
            foreach (var cb in GetCheckBoxArray())
            {
                cb.IsChecked = true;
            }
        }

        /// <summary>
        /// 获取所有A/B组CheckBox的数组（顺序：A1-A40 → B1-B40）
        /// </summary>
        private CheckBox[] GetCheckBoxArray()
        {
            return new CheckBox[] {
                // A组（A1-A40）
                CheckBox_A1, CheckBox_A2, CheckBox_A3, CheckBox_A4, CheckBox_A5,
                CheckBox_A6, CheckBox_A7, CheckBox_A8, CheckBox_A9, CheckBox_A10,
                CheckBox_A11, CheckBox_A12, CheckBox_A13, CheckBox_A14, CheckBox_A15,
                CheckBox_A16, CheckBox_A17, CheckBox_A18, CheckBox_A19, CheckBox_A20,
                CheckBox_A21, CheckBox_A22, CheckBox_A23, CheckBox_A24, CheckBox_A25,
                CheckBox_A26, CheckBox_A27, CheckBox_A28, CheckBox_A29, CheckBox_A30,
                CheckBox_A31, CheckBox_A32, CheckBox_A33, CheckBox_A34, CheckBox_A35,
                CheckBox_A36, CheckBox_A37, CheckBox_A38, CheckBox_A39, CheckBox_A40,
                
                // B组（B1-B40）
                CheckBox_B1, CheckBox_B2, CheckBox_B3, CheckBox_B4, CheckBox_B5,
                CheckBox_B6, CheckBox_B7, CheckBox_B8, CheckBox_B9, CheckBox_B10,
                CheckBox_B11, CheckBox_B12, CheckBox_B13, CheckBox_B14, CheckBox_B15,
                CheckBox_B16, CheckBox_B17, CheckBox_B18, CheckBox_B19, CheckBox_B20,
                CheckBox_B21, CheckBox_B22, CheckBox_B23, CheckBox_B24, CheckBox_B25,
                CheckBox_B26, CheckBox_B27, CheckBox_B28, CheckBox_B29, CheckBox_B30,
                CheckBox_B31, CheckBox_B32, CheckBox_B33, CheckBox_B34, CheckBox_B35,
                CheckBox_B36, CheckBox_B37, CheckBox_B38, CheckBox_B39, CheckBox_B40
            };
        }
        #endregion

        #region 设备刷新方法（优化异常处理和代码简洁性）
        /// <summary>
        /// 刷新I2C设备列表
        /// </summary>
        private bool RefreshI2CPorts()
        {
            try
            {
                // 初始化并更新USB设备
                XChipUSB.UsbIniDevice();
                XChipUSB.UsbUpdateDevice();

                // 获取设备数量（小于0表示获取失败）
                int deviceCount = XChipUSB.UsbGetDeviceNum();
                if (deviceCount < 0) return false;

                // 获取所有设备信息
                DeviceInfos[] deviceInfos = XChipUSB.UsbGetAllDeviceInfoViaMultiplex(deviceCount);
                I2CPortList.Clear();

                // 过滤无效设备（VID/PID为空或全0），添加有效设备到列表
                foreach (var device in deviceInfos)
                {
                    if (string.IsNullOrEmpty(device.VID) || string.IsNullOrEmpty(device.PID) ||
                        device.VID == "\0\0\0\0" || device.PID == "\0\0\0\0")
                        continue;

                    I2CPortList.Add(new USBDeviceModel
                    {
                        DeviceName = device.DeviceName.TrimEnd('\0'),  // 去除末尾空字符
                        PID = device.PID,
                        VID = device.VID,
                        DevicePath = device.DevicePath,
                        IsOpen = false
                    });
                }
                return true;
            }
            catch (Exception ex)
            {
                AppendToLog(usbI2cLogTextBox, $"刷新I2C设备列表失败: {ex.Message}");
                return false;
            }
        }

        /// <summary>
        /// 刷新USB-I2C设备状态
        /// </summary>
        private void RefreshI2CUsbPorts()
        {
            try
            {
                // 先关闭现有设备，避免资源占用
                USBIOXdll.USBIO_CloseDevice(_i2cUsbIndex);

                // 尝试重新打开设备，更新状态
                var openResult = USBIOXdll.USBIO_OpenDevice(_i2cUsbIndex);
                IsUsbI2cOpen = (int)openResult != -1;
            }
            catch (Exception ex)
            {
                AppendToLog(usbI2cLogTextBox, $"刷新USB-I2C设备失败: {ex.Message}");
            }
        }
        #endregion

        #region 设备连接/断开事件（优化逻辑判断和错误提示）
        /// <summary>
        /// 刷新设备列表按钮点击事件
        /// </summary>
        private void RefreshToggleButton_Click(object sender, RoutedEventArgs e)
        {
            if (RefreshI2CPorts())
                MessageBox.Show("I2C设备列表已刷新", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
            else
                MessageBox.Show("I2C设备列表刷新失败", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
        }

        /// <summary>
        /// I2C设备打开按钮（Checked状态）
        /// </summary>
        private void OpenToggleButton_Checked(object sender, RoutedEventArgs e)
        {
            try
            {
                // 校验：是否选择设备
                if (SelectedI2CPort == null)
                {
                    MessageBox.Show("请先选择要连接的I2C设备", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                    openToggleButton.IsChecked = false;
                    return;
                }

                // 初始化USB设备
                XChipUSB.UsbIniDevice();
                XChipUSB.UsbUpdateDevice();

                // 查找设备索引（优化：用IndexOf替代循环）
                int deviceIndex = I2CPortList.IndexOf(SelectedI2CPort);
                if (deviceIndex == -1)
                {
                    MessageBox.Show("选中的I2C设备未在列表中找到", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                    openToggleButton.IsChecked = false;
                    return;
                }

                // 尝试选择设备
                IsUsbOpen = XChipUSB.UsbSelectDevice(deviceIndex);
                if (IsUsbOpen)
                {
                    AppendToLog(usbI2cLogTextBox, $"I2C设备「{SelectedI2CPort.DeviceName}」打开成功！");
                    SelectedI2CPort.IsOpen = true;
                }
                else
                {
                    AppendToLog(usbI2cLogTextBox, $"I2C设备「{SelectedI2CPort.DeviceName}」打开失败！");
                    openToggleButton.IsChecked = false;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"I2C设备连接失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                openToggleButton.IsChecked = false;
            }
        }

        /// <summary>
        /// I2C设备关闭按钮（Unchecked状态）
        /// </summary>
        private void OpenToggleButton_Unchecked(object sender, RoutedEventArgs e)
        {
            try
            {
                // 关闭设备并更新状态
                XChipUSB.UsbDestroyUSB();
                IsUsbOpen = false;

                if (SelectedI2CPort != null)
                {
                    SelectedI2CPort.IsOpen = false;
                    AppendToLog(usbI2cLogTextBox, $"I2C设备「{SelectedI2CPort.DeviceName}」已关闭");
                }
            }
            catch (Exception ex)
            {
                AppendToLog(usbI2cLogTextBox, $"关闭I2C设备失败: {ex.Message}");
            }
        }

        /// <summary>
        /// USB-I2C设备打开按钮（Checked状态）
        /// </summary>
        //private void UsbOpenToggleButton_Checked(object sender, RoutedEventArgs e)
        //{
        //    try
        //    {
        //        // 尝试打开USB-I2C设备
        //        var openResult = USBIOXdll.USBIO_OpenDevice(_i2cUsbIndex);
        //        if ((int)openResult != -1)
        //        {
        //            IsUsbI2cOpen = true;
        //            usbI2cstatus.Content = "USB2I2C 设备打开成功！";
        //            usbI2cstatus.Foreground = Brushes.Green;
        //            AppendToLog(usbI2cLogTextBox, "USB2I2C 设备打开成功！");
        //        }
        //        else
        //        {
        //            IsUsbI2cOpen = false;
        //            usbI2cstatus.Content = "USB2I2C 设备打开失败！";
        //            usbI2cstatus.Foreground = Brushes.Red;
        //            AppendToLog(usbI2cLogTextBox, "USB2I2C 设备打开失败！");
        //            usbOpenToggleButton.IsChecked = false;
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        MessageBox.Show($"USB-I2C设备连接失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
        //        usbOpenToggleButton.IsChecked = false;
        //    }
        //}

        /// <summary>
        /// USB-I2C设备关闭按钮（Unchecked状态）
        /// </summary>
        //private void UsbOpenToggleButton_Unchecked(object sender, RoutedEventArgs e)
        //{
        //    try
        //    {
        //        // 关闭设备并更新状态
        //        USBIOXdll.USBIO_CloseDevice(_i2cUsbIndex);
        //        IsUsbI2cOpen = false;

        //        usbI2cstatus.Content = "USB2I2C 设备已关闭";
        //        usbI2cstatus.Foreground = Brushes.Gray;
        //        AppendToLog(usbI2cLogTextBox, "USB2I2C 设备已关闭");
        //    }
        //    catch (Exception ex)
        //    {
        //        AppendToLog(usbI2cLogTextBox, $"关闭USB-I2C设备失败: {ex.Message}");
        //    }
        //}
        #endregion

        #region I2C读写操作（优化参数校验和日志输出）
        /// <summary>
        /// I2C写入按钮点击事件
        /// </summary>
        private void I2cWriteBtn_Click(object sender, RoutedEventArgs e)
        {
            // 校验：设备是否已打开
            if (!IsUsbOpen)
            {
                MessageBox.Show("请先打开I2C设备", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }

            try
            {
                // 校验并转换输入参数（16进制）
                if (!uint.TryParse(i2cIdTextBox.Text, System.Globalization.NumberStyles.HexNumber, null, out uint deviceId))
                {
                    MessageBox.Show("I2C设备ID格式错误（需为16进制）", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                    return;
                }
                if (!uint.TryParse(i2cAddrTextBox.Text, System.Globalization.NumberStyles.HexNumber, null, out uint regAddr))
                {
                    MessageBox.Show("寄存器地址格式错误（需为16进制）", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                    return;
                }
                if (!uint.TryParse(i2cValTextBox.Text, System.Globalization.NumberStyles.HexNumber, null, out uint writeData))
                {
                    MessageBox.Show("写入数据格式错误（需为16进制）", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                    return;
                }

                // 执行I2C批量写入
                bool writeSuccess = XChipUSB.UsbI2CBulkWrite(regAddr, new[] { writeData }, 1, deviceId);
                if (writeSuccess)
                    AppendToLog(usbI2cLogTextBox, $"I2C写入成功 | 设备ID:0x{deviceId:X} | 地址:0x{regAddr:X} | 数据:0x{writeData:X2}");
                else
                    AppendToLog(usbI2cLogTextBox, $"I2C写入失败 | 设备ID:0x{deviceId:X} | 地址:0x{regAddr:X}");
            }
            catch (Exception ex)
            {
                MessageBox.Show($"I2C写入异常: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        /// <summary>
        /// I2C读取按钮点击事件
        /// </summary>
        private void I2cReadBtn_Click(object sender, RoutedEventArgs e)
        {
            // 校验：设备是否已打开
            if (!IsUsbOpen)
            {
                MessageBox.Show("请先打开I2C设备", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }

            try
            {
                // 校验并转换输入参数（16进制）
                if (!uint.TryParse(i2cIdTextBox.Text, System.Globalization.NumberStyles.HexNumber, null, out uint deviceId))
                {
                    MessageBox.Show("I2C设备ID格式错误（需为16进制）", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                    return;
                }
                if (!uint.TryParse(i2cAddrTextBox.Text, System.Globalization.NumberStyles.HexNumber, null, out uint regAddr))
                {
                    MessageBox.Show("寄存器地址格式错误（需为16进制）", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                    return;
                }

                // 执行I2C批量读取
                uint[] readBuffer = new uint[1];
                bool readSuccess = XChipUSB.UsbI2CBulkRead(regAddr, readBuffer, 1, deviceId);

                if (readSuccess)
                {
                    i2cValTextBox.Text = readBuffer[0].ToString("X2");  // 显示读取结果（16进制）
                    AppendToLog(usbI2cLogTextBox, $"I2C读取成功 | 设备ID:0x{deviceId:X} | 地址:0x{regAddr:X} | 数据:0x{readBuffer[0]:X2}");
                }
                else
                {
                    AppendToLog(usbI2cLogTextBox, $"I2C读取失败 | 设备ID:0x{deviceId:X} | 地址:0x{regAddr:X}");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"I2C读取异常: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        /// <summary>
        /// USB-I2C写入按钮点击事件
        /// </summary>
        private void UsbI2cWriteBtn_Click(object sender, RoutedEventArgs e)
        {
            // 校验：设备是否已打开
            if (!PortHelper.IsOpen)
            {
                MessageBox.Show("串口未打开", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }

            try
            {
                //// 校验并转换输入参数（16进制）
                //if (!int.TryParse(usbI2cIdTextBox.Text, System.Globalization.NumberStyles.HexNumber, null, out int deviceNoInt) ||
                //    deviceNoInt < 0 || deviceNoInt > 255)
                //{
                //    MessageBox.Show("USB-I2C设备号格式错误（需为0-255的16进制）", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                //    return;
                //}
                if (!uint.TryParse(usbI2cAddrTextBox.Text, System.Globalization.NumberStyles.HexNumber, null, out uint regAddr))
                {
                    MessageBox.Show("寄存器地址格式错误（需为16进制）", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                    return;
                }
                if (!byte.TryParse(usbI2cValTextBox.Text, System.Globalization.NumberStyles.HexNumber, null, out byte writeData))
                {
                    MessageBox.Show("写入数据格式错误（需为0-255的16进制）", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                    return;
                }
                int byte_sel = (int)(regAddr) & 0x3;
                byte_sel = byte_sel * 8;
                uint reg_data = Convert.ToUInt32(usbI2cValTextBox.Text, 16);
                reg_data = reg_data & 0xff;
                reg_data = reg_data << byte_sel;
                long test_value1 = (long)0x82000000;
                uint test_value2 = (uint)0x00000000;
                uint FUNCT_SEL_ADDR = (uint)(test_value1 + test_value2);
                PortHelper.SendRegDataARM(0x1, FUNCT_SEL_ADDR, 0);

                PortHelper.SendRegDataARM(0x21, regAddr, reg_data);
                AppendToLog(usbI2cLogTextBox, $"W:0x{usbI2cAddrTextBox.Text} 0x{usbI2cValTextBox.Text}");

            }
            catch (Exception ex)
            {
                MessageBox.Show($"USB-I2C写入异常: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        /// <summary>
        /// USB-I2C读取按钮点击事件
        /// </summary>
        private void UsbI2cReadBtn_Click(object sender, RoutedEventArgs e)
        {
            // 校验：设备是否已打开
            //if (!IsUsbI2cOpen)
            //{
            //    MessageBox.Show("请先打开USB-I2C设备", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            //    return;
            //}
            if (!PortHelper.IsOpen)
            {
                MessageBox.Show("串口未打开", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }

            try
            {
                // 校验并转换输入参数（16进制）
                //if (!int.TryParse(usbI2cIdTextBox.Text, System.Globalization.NumberStyles.HexNumber, null, out int deviceNoInt) ||
                //    deviceNoInt < 0 || deviceNoInt > 255)
                //{
                //    MessageBox.Show("USB-I2C设备号格式错误（需为0-255的16进制）", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                //    return;
                //}
                if (!uint.TryParse(usbI2cAddrTextBox.Text, System.Globalization.NumberStyles.HexNumber, null, out uint regAddr))
                {
                    MessageBox.Show("寄存器地址格式错误（需为16进制）", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                    return;
                }

                // 执行USB-I2C读取（移除using语句，因为I2CManager未实现IDisposable）
                //byte deviceNo = (byte)deviceNoInt;
                //var i2cManager = new I2CManager(_i2cUsbIndex);
                //if (i2cManager.GetI2CData(regAddr, deviceNo, 1, out byte[] readData))
                //{
                //    usbI2cValTextBox.Text = readData[0].ToString("X2");  // 显示读取结果（16进制）
                //    AppendToLog(usbI2cLogTextBox, $"USB-I2C读取成功 | 设备号:0x{deviceNo:X2} | 地址:0x{regAddr:X} | 数据:0x{readData[0]:X2}");
                //}
                //else
                //{
                //    AppendToLog(usbI2cLogTextBox, $"USB-I2C读取失败 | 设备号:0x{deviceNo:X2} | 地址:0x{regAddr:X}");
                //}
                long test_value1 = (long)0x82000000;
                uint test_value2 = (uint)0x00000000;
                uint FUNCT_SEL_ADDR = (uint)(test_value1 + test_value2);

                PortHelper.SendRegData(0x1, FUNCT_SEL_ADDR, 0);
                uint reg_address = Convert.ToUInt32(usbI2cAddrTextBox.Text, 16);
                uint recvdata = 0;
                if (reg_address % 4 != 0)
                {
                    MessageBox.Show("输入地址需要以\"0\"\"4\"\"8\"\"c\"结尾", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                    return;
                }
                PortHelper.ReadRegData(0x11, reg_address, ref recvdata);
                this.usbI2cValTextBox.Text = $"{(recvdata >> 24 & 0xff).ToString("X2")}{(recvdata >> 16 & 0xff).ToString("X2")}{(recvdata >> 8 & 0xff).ToString("X2")}{(recvdata & 0xff).ToString("X2")}";
                AppendToLog(usbI2cLogTextBox, $"R:0x{(reg_address + 0).ToString("X2")} 0x{(recvdata >> 24 & 0xff).ToString("X2")}");
                AppendToLog(usbI2cLogTextBox, $"R:0x{(reg_address + 1).ToString("X2")} 0x{(recvdata >> 16 & 0xff).ToString("X2")}");
                AppendToLog(usbI2cLogTextBox, $"R:0x{(reg_address + 2).ToString("X2")} 0x{(recvdata >> 8 & 0xff).ToString("X2")}");
                AppendToLog(usbI2cLogTextBox, $"R:0x{(reg_address + 3).ToString("X2")} 0x{(recvdata & 0xff).ToString("X2")}");

            }
            catch (Exception ex)
            {
                MessageBox.Show($"USB-I2C读取异常: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
        #endregion

        #region 日志操作（统一日志格式，优化线程安全）
        /// <summary>
        /// 向指定日志文本框追加日志（线程安全，支持UI调度）
        /// </summary>
        private void AppendToLog(TextBox logTextBox, string message)
        {
            if (logTextBox == null || Dispatcher == null) return;

            // 确保在UI线程更新日志
            logTextBox.Dispatcher.Invoke(() =>
            {
                string logEntry = $"[{DateTime.Now:yyyy-MM-dd HH:mm:ss}] {message}{Environment.NewLine}";
                logTextBox.AppendText(logEntry);
                logTextBox.ScrollToEnd();  // 自动滚动到最新日志
            });
        }

       

        /// <summary>
        /// 清空USB-I2C日志按钮
        /// </summary>
        private void ClearUsbI2cLog_Click(object sender, RoutedEventArgs e)
        {
            usbI2cLogTextBox.Clear();
        }

        /// <summary>
        /// 导出I2C日志按钮
        /// </summary>
        private void ExportI2cLog_Click(object sender, RoutedEventArgs e)
        {
            ExportLog(usbI2cLogTextBox, "I2C_Log_");
        }

        /// <summary>
        /// 导出USB-I2C日志按钮
        /// </summary>
        private void ExportUsbI2cLog_Click(object sender, RoutedEventArgs e)
        {
            ExportLog(usbI2cLogTextBox, "USB_I2C_Log_");
        }

        /// <summary>
        /// 通用日志导出方法（抽取重复逻辑）
        /// </summary>
        private void ExportLog(TextBox logTextBox, string logPrefix)
        {
            if (string.IsNullOrEmpty(logTextBox.Text))
            {
                MessageBox.Show("日志为空，无需导出", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                return;
            }

            // 打开保存文件对话框
            var saveDialog = new SaveFileDialog
            {
                FileName = $"{logPrefix}{DateTime.Now:yyyyMMdd_HHmmss}.txt",
                Filter = "文本文件 (*.txt)|*.txt|所有文件 (*.*)|*.*",
                InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
                Title = "导出日志文件"
            };

            if (saveDialog.ShowDialog() == true)
            {
                try
                {
                    // 写入日志到文件
                    File.WriteAllText(saveDialog.FileName, logTextBox.Text);
                    MessageBox.Show($"日志已成功导出到：{saveDialog.FileName}", "成功", MessageBoxButton.OK, MessageBoxImage.Information);
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"日志导出失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
        }
        #endregion

        #region 测试流程（修正异步调用、完善测试逻辑）
        /// <summary>
        /// USB-I2C设备搜索按钮（搜索I2C从设备地址）
        /// </summary>
        private void UsbSearchBtn_Click(object sender, RoutedEventArgs e)
        {
            // 校验：设备是否已打开
            if (!IsUsbI2cOpen)
            {
                MessageBox.Show("请先打开USB-I2C设备", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }



            try
            {
                I2CUsbPortList.Clear();
                string searchResult = "搜索到的I2C设备地址：\n";

                // 搜索I2C地址范围（0x03-0x77，偶数地址）
                for (uint addr = 0x03; addr <= 0x77; addr++)
                {
                    // I2C地址需左移1位（最低位为读写位）
                    byte[] writeBuf = { (byte)(addr << 1) };
                    byte[] readBuf = new byte[1];

                    // 尝试读取设备响应（判断设备是否存在）
                    if (USBIOXdll.USBIO_StreamI2C(_i2cUsbIndex, 1, writeBuf, 1, readBuf) &&
                        readBuf[0] != 0xFF && addr % 2 == 0)
                    {
                        string addrHex = addr.ToString("X2");
                        I2CUsbPortList.Add(addrHex);
                        searchResult += $"0x{addrHex}\n";
                    }
                }

                // 输出搜索结果
                AppendToLog(usbI2cLogTextBox, searchResult.TrimEnd('\n'));
                if (I2CUsbPortList.Count == 0)
                    AppendToLog(usbI2cLogTextBox, "未搜索到任何I2C设备");
            }
            catch (Exception ex)
            {
                AppendToLog(usbI2cLogTextBox, $"I2C设备搜索失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 异步执行单个通道测试（修正async/await调用，避免异步空转）
        /// </summary>
        private async Task CheckTestAsync(int channelIndex, CancellationToken cancellationToken)
        {
            // 校验：测试是否已取消
            if (cancellationToken.IsCancellationRequested)
                return;

            // 区分A/B组通道（0-39为A组，40-79为B组）
            string channelName = channelIndex < 40 ? $"A{channelIndex + 1}" : $"B{channelIndex - 39}";
            AppendToLog(TestTextBox, $"{channelName} 开始测试");

            try
            {
                // 1. 写入GPIO控制寄存器（使用预设的测试值）
                if (channelIndex >= 0 && channelIndex < _loopTestValue.Length)
                {
                    uint testValue = (uint)_loopTestValue[channelIndex];
                    AppendToLog(TestTextBox, $"{channelName} 写入GPIO控制寄存器：0x{testValue:X8}");

                    // 此处需根据实际硬件补充I2C写入逻辑（示例：假设写入到80500208地址）
                    bool writeSuccess = XChipUSB.UsbRegisterWrite(0x80500208, testValue, true);
                    if (writeSuccess)
                    {
                        AppendToLog(TestTextBox, $"寄存器写入成功 | 地址:0x80500208 | 数据:0x{testValue:X8}");
                    }
                    else
                    {
                        AppendToLog(TestTextBox, $"寄存器写入失败 | 地址:0x80500208");
                    }
                }
                await Task.Delay(500, cancellationToken); // 等待硬件响应
                AppendToLog(TestTextBox, $"{channelName} GPIO控制寄存器写入完成");

                // 2. 读取测试结果（示例：假设从0x80500209地址读取）
                AppendToLog(TestTextBox, $"{channelName} 读取测试结果");
                byte[] readResult = new byte[1];
                if (IsUsbI2cOpen)
                {
                    // 移除using语句，因为I2CManager未实现IDisposable
                    var i2cManager = new I2CManager(_i2cUsbIndex);
                    bool readSuccess = i2cManager.GetI2CData(0x80500209, 0x00, 1, out readResult);
                    if (!readSuccess)
                    {
                        AppendToLog(TestTextBox, $"{channelName} 测试结果读取失败");
                        _testResultTemp[channelIndex] = false;
                        return;
                    }
                }
                await Task.Delay(500, cancellationToken); // 等待读取完成
                AppendToLog(TestTextBox, $"{channelName} 测试结果：0x{readResult[0]:X2}");

                // 3. 判断并保存测试结果（假设0x00为成功，其他为失败，需根据实际调整）
                bool testPass = readResult[0] == 0x00;
                _testResultTemp[channelIndex] = testPass;
                _testResultFinal[channelIndex] = testPass; // 同步到最终结果
                AppendToLog(TestTextBox, $"{channelName} 测试{(testPass ? "通过" : "失败")}");
            }
            catch (OperationCanceledException)
            {
                AppendToLog(TestTextBox, $"{channelName} 测试被取消");
                _testResultTemp[channelIndex] = null;
                _testResultFinal[channelIndex] = null;
            }
            catch (Exception ex)
            {
                AppendToLog(TestTextBox, $"{channelName} 测试异常: {ex.Message}");
                _testResultTemp[channelIndex] = false;
                _testResultFinal[channelIndex] = false;
            }
        }

        /// <summary>
        /// 打印最终测试结果（完善结果展示逻辑）
        /// </summary>
        private void ResultPrint()
        {
            if (_testResultFinal.All(r => r == null))
            {
                AppendToLog(TestTextBox, "暂无测试结果可打印");
                return;
            }

            // 打印A组结果（A1-A40）
            AppendToLog(TestTextBox, "=================== A组测试结果 ===================");
            string aResult = "\n";
            for (int i = 0; i < 40; i++)
            {
                string status;
                // 使用switch语句替代C# 8.0+的模式匹配，兼容C# 7.3
                switch (_testResultFinal[i])
                {
                    case true:
                        status = "✓";
                        break;
                    case false:
                        status = "✗";
                        break;
                    default:
                        status = "?";
                        break;
                }
                aResult += $"A{i + 1}:{status}  ";
                if ((i + 1) % 8 == 0) // 每8个通道换行，优化显示
                    aResult += "\n";
            }
            AppendToLog(TestTextBox, aResult.TrimEnd('\n'));

            // 打印B组结果（B1-B40）
            AppendToLog(TestTextBox, "=================== B组测试结果 ===================");
            string bResult = "\n";
            for (int i = 40; i < 80; i++)
            {
                string status;
                // 使用switch语句替代C# 8.0+的模式匹配，兼容C# 7.3
                switch (_testResultFinal[i])
                {
                    case true:
                        status = "✓";
                        break;
                    case false:
                        status = "✗";
                        break;
                    default:
                        status = "?";
                        break;
                }
                bResult += $"B{i - 39}:{status}  ";
                if ((i - 39) % 8 == 0) // 每8个通道换行，优化显示
                    bResult += "\n";
            }
            AppendToLog(TestTextBox, bResult.TrimEnd('\n'));

            // 统计测试结果
            int passCount = _testResultFinal.Count(r => r == true);
            int failCount = _testResultFinal.Count(r => r == false);
            int untestedCount = _testResultFinal.Count(r => r == null);
            AppendToLog(TestTextBox, $"=================== 测试统计 ===================");
            AppendToLog(TestTextBox, $"总通道数：80 | 通过：{passCount} | 失败：{failCount} | 未测试：{untestedCount}");
        }

        /// <summary>
        /// 开始测试按钮点击事件
        /// </summary>
        private void TestStartBtn_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                //校验：USB - I2C设备是否已打开
                //if (!IsUsbI2cOpen)
                //{
                //    MessageBox.Show("请先打开USB-I2C设备", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                //    return;
                //}


                // 校验：设备是否已打开
                if (!IsUsbOpen)
                {
                    MessageBox.Show("请先打开I2C设备", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                    return;
                }

                // 初始化测试状态
                AppendToLog(TestTextBox, "=================== 开始新测试 ===================");
                TestStartBtn.IsEnabled = false;
                TestStartEnd.IsEnabled = true;

                // 使用循环替代Array.Fill，兼容旧版本框架
                for (int i = 0; i < _testResultTemp.Length; i++)
                    _testResultTemp[i] = null;

                for (int i = 0; i < _testResultFinal.Length; i++)
                    _testResultFinal[i] = null;

                // 保存CheckBox选中状态（确定需要测试的通道）
                SaveCheckBoxStates();
                AppendToLog(TestTextBox, "已获取测试通道使能状态");

                // 打印测试通道列表（A组）
                AppendToLog(TestTextBox, "【A组测试通道】");
                string aTestChannels = "";
                for (int i = 0; i < 40; i++)
                {
                    if (_testEnCheckboxStates[i] == true)
                        aTestChannels += $"A{i + 1}  ";
                }
                AppendToLog(TestTextBox, string.IsNullOrEmpty(aTestChannels) ? "无" : aTestChannels.TrimEnd());

                // 打印测试通道列表（B组）
                AppendToLog(TestTextBox, "【B组测试通道】");
                string bTestChannels = "";
                for (int i = 40; i < 80; i++)
                {
                    if (_testEnCheckboxStates[i] == true)
                        bTestChannels += $"B{i - 39}  ";
                }
                AppendToLog(TestTextBox, string.IsNullOrEmpty(bTestChannels) ? "无" : bTestChannels.TrimEnd());

                // 校验：是否选择了测试通道
                if (!_testEnCheckboxStates.Any(s => s == true))
                {
                    MessageBox.Show("未选择任何测试通道，请先勾选需要测试的通道", "提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                    TestStartBtn.IsEnabled = true;
                    TestStartEnd.IsEnabled = false;
                    return;
                }

                //测试准备
                AppendToLog(TestTextBox, $"测试准备，初始化Xchip 读写设置GPIO。");
                bool writeSuccess = XChipUSB.UsbRegisterWrite(0x805000f0, 0x00005500, true);
                if (writeSuccess)
                {
                    AppendToLog(TestTextBox, $"寄存器写入成功 | 地址:0x805000f0 | 数据:0x{0x00005500:X8}");
                }
                else
                {
                    AppendToLog(TestTextBox, $"寄存器写入失败 | 地址:0x805000f0");
                }

                 writeSuccess = XChipUSB.UsbRegisterWrite(0x80500200, 0x0000c70f, true);
                if (writeSuccess)
                {
                    AppendToLog(TestTextBox, $"寄存器写入成功 | 地址:0x80500200 | 数据:0x{0x0000c70f:X8}");
                }
                else
                {
                    AppendToLog(TestTextBox, $"寄存器写入失败 | 地址:0x80500200");
                }

                 writeSuccess = XChipUSB.UsbRegisterWrite(0x80500204, 0x0000c70f, true);
                if (writeSuccess)
                {
                    AppendToLog(TestTextBox, $"寄存器写入成功 | 地址:0x80500204 | 数据:0x{0x0000c70f:X8}");
                }
                else
                {
                    AppendToLog(TestTextBox, $"寄存器写入失败 | 地址:0x80500204");
                }


                // 创建取消令牌，启动测试任务
                _cancellationTokenSource?.Dispose(); // 释放旧令牌
                _cancellationTokenSource = new CancellationTokenSource();
                Task.Run(() => TestLoopAsync(_cancellationTokenSource.Token), _cancellationTokenSource.Token);
            }
            catch (Exception ex)
            {
                AppendToLog(TestTextBox, $"测试启动失败: {ex.Message}");
                TestStartBtn.IsEnabled = true;
                TestStartEnd.IsEnabled = false;
            }
        }

        /// <summary>
        /// 停止测试按钮点击事件
        /// </summary>
        private void TestStartEnd_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                // 请求取消测试
                _cancellationTokenSource?.Cancel();
                AppendToLog(TestTextBox, "正在停止测试...");
                TestStartBtn.IsEnabled = true;
                TestStartEnd.IsEnabled = false;
            }
            catch (Exception ex)
            {
                AppendToLog(TestTextBox, $"测试停止失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 测试循环（异步执行，支持取消）
        /// </summary>
        private async Task TestLoopAsync(CancellationToken cancellationToken)
        {
            try
            {
                int loopCount = 0;
                while (!cancellationToken.IsCancellationRequested)
                {
                    loopCount++;
                    await Dispatcher.InvokeAsync(() =>
                    {
                        statusText.Text = $"测试中 | 循环次数: {loopCount}";
                        AppendToLog(TestTextBox, $"=================== 测试循环 {loopCount} ===================");
                    }, System.Windows.Threading.DispatcherPriority.Normal, cancellationToken);

                    // 执行选中通道的测试（只测试CheckBox勾选的通道）
                    for (int i = 0; i < 80; i++)
                    {
                        if (cancellationToken.IsCancellationRequested)
                            break;

                        if (_testEnCheckboxStates[i] == true)
                        {
                            await CheckTestAsync(i, cancellationToken);
                        }
                    }

                    // 打印当前循环的测试结果
                    await Dispatcher.InvokeAsync(ResultPrint, System.Windows.Threading.DispatcherPriority.Normal, cancellationToken);

                    // 等待下一次循环（可根据需求调整间隔）
                    await Task.Delay(1000, cancellationToken);
                }
            }
            catch (OperationCanceledException)
            {
                // 测试被手动取消
                await Dispatcher.InvokeAsync(() =>
                {
                    statusText.Text = "测试已取消";
                    AppendToLog(TestTextBox, "=================== 测试已手动取消 ===================");
                });
            }
            catch (Exception ex)
            {
                // 测试异常
                await Dispatcher.InvokeAsync(() =>
                {
                    statusText.Text = "测试异常";
                    AppendToLog(TestTextBox, $"=================== 测试异常 ===================\n异常信息: {ex.Message}");
                });
            }
            finally
            {
                // 恢复UI状态
                await Dispatcher.InvokeAsync(() =>
                {
                    TestStartBtn.IsEnabled = true;
                    TestStartEnd.IsEnabled = false;
                    statusText.Text = "测试已停止";
                });
            }
        }
        #endregion

        #region 辅助方法和资源释放
        /// <summary>
        /// 更新状态栏文本
        /// </summary>
        private void UpdateStatusText()
        {
            var statusParts = new List<string> { "就绪" };
            if (IsUsbOpen) statusParts.Add("I2C设备已连接");
            if (IsUsbI2cOpen) statusParts.Add("USB2I2C设备已连接");
            statusText.Text = string.Join(" | ", statusParts);
        }

        /// <summary>
        /// 窗口关闭时释放资源
        /// </summary>
        protected override void OnClosed(EventArgs e)
        {
            // 取消并释放测试任务令牌
            _cancellationTokenSource?.Cancel();
            _cancellationTokenSource?.Dispose();

            // 关闭所有设备连接
            if (IsUsbOpen)
                XChipUSB.UsbDestroyUSB();
            if (IsUsbI2cOpen)
                USBIOXdll.USBIO_CloseDevice(_i2cUsbIndex);

            base.OnClosed(e);
        }

        /// <summary>
        /// INotifyPropertyChanged接口实现
        /// </summary>
        public event PropertyChangedEventHandler PropertyChanged;
        protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
        #endregion

        /// <summary>
        /// USB设备信息模型（实现INotifyPropertyChanged，支持UI绑定）
        /// </summary>
        public class USBDeviceModel : INotifyPropertyChanged
        {
            private bool _isOpen;

            public string DeviceName { get; set; }
            public string PID { get; set; }
            public string VID { get; set; }
            public string DevicePath { get; set; }

            public bool IsOpen
            {
                get => _isOpen;
                set
                {
                    _isOpen = value;
                    OnPropertyChanged();
                }
            }

            /// <summary>
            /// 列表显示时的文本（设备名称）
            /// </summary>
            public override string ToString() => DeviceName;

            #region INotifyPropertyChanged实现
            public event PropertyChangedEventHandler PropertyChanged;
            protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
            {
                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
            }
            #endregion
        }

        /// <summary>
        /// 寄存器写
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void RegisterWriteBtn_Click(object sender, RoutedEventArgs e)
        {
            // 校验：设备是否已打开
            if (!IsUsbOpen)
            {
                MessageBox.Show("请先打开I2C设备", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }

            try
            {
               
                if (!uint.TryParse(i2cAddrTextBox.Text, System.Globalization.NumberStyles.HexNumber, null, out uint regAddr))
                {
                    MessageBox.Show("寄存器地址格式错误（需为16进制）", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                    return;
                }
                if (!uint.TryParse(i2cValTextBox.Text, System.Globalization.NumberStyles.HexNumber, null, out uint writeData))
                {
                    MessageBox.Show("写入数据格式错误（需为16进制）", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                    return;
                }

                // 执行寄存器批量写入
                bool writeSuccess = XChipUSB.UsbRegisterWrite(regAddr, writeData , false);
                if (writeSuccess)
                    AppendToLog(usbI2cLogTextBox, $"寄存器写入成功 | 地址:0x{regAddr:X} | 数据:0x{writeData:X2}");
                else
                    AppendToLog(usbI2cLogTextBox, $"寄存器写入失败 | 地址:0x{regAddr:X}");
            }
            catch (Exception ex)
            {
                MessageBox.Show($"寄存器写入异常: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
        /// <summary>
        /// 寄存器读
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void RegisterReadBtn_Click(object sender, RoutedEventArgs e)
        {
            // 校验：设备是否已打开
            if (!IsUsbOpen)
            {
                MessageBox.Show("请先打开I2C设备", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }

            try
            {
              
                if (!uint.TryParse(i2cAddrTextBox.Text, System.Globalization.NumberStyles.HexNumber, null, out uint regAddr))
                {
                    MessageBox.Show("寄存器地址格式错误（需为16进制）", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                    return;
                }

                // 执行寄存器批量读取
                uint readBuffer = new uint();
                bool readSuccess = XChipUSB.UsbRegisterRead(regAddr,ref readBuffer, (bool)is32.IsChecked);

                if (readSuccess)
                {
                    i2cValTextBox.Text = readBuffer.ToString("X2");  // 显示读取结果（16进制）
                    AppendToLog(usbI2cLogTextBox, $"寄存器读取成功  | 地址:0x{regAddr:X} | 数据:0x{readBuffer:X2}");
                }
                else
                {
                    AppendToLog(usbI2cLogTextBox, $"寄存器读取失败 | 地址:0x{regAddr:X}");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"寄存器读取异常: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        /// <summary>
        /// 刷新串口
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void refreshButton_Click(object sender, RoutedEventArgs e)
        {
           var list = PortHelper.GetPorts();
            foreach (var item in list)
            {
                RegisterPortList.Add(item.Dis);
            }
        }

        /// <summary>
        /// 打开串口
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void RegisterButton_Checked(object sender, RoutedEventArgs e)
        {
            try
            {
                string msg = string.Empty;

                // 配置串口参数
                PortHelper.ConfigComType.PortName = SelectedRegisterPort;
                PortHelper.ConfigComType.BaudRate = SelectedBaudRate;
                PortHelper.ConfigComType.DataBits = SelectedDataBits;
                PortHelper.ConfigComType.StopBits = (PortHelper.StopBits)1;
                PortHelper.ConfigComType.Parity = (PortHelper.Parity)2;

                // 打开串口
                PortHelper.OpenCom(out msg);

                AppendToLog(usbI2cLogTextBox, msg);

                if (PortHelper.IsOpen)
                {
                    RegisterButtonText = "关闭";
                    RegisterButtonColor = new SolidColorBrush(Color.FromRgb(255, 182, 193)); // LightPink
                }
                else
                {
                    RegisterButtonText = "打开";
                    RegisterButtonColor = Brushes.LimeGreen;
                }
            }
            catch (Exception ex)
            {
                AppendToLog(usbI2cLogTextBox, ex.Message.ToString());
            }

        }
        /// <summary>
        /// 关闭串口
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void RegisterButton_Unchecked(object sender, RoutedEventArgs e)
        {
            try
            {
                string msg = string.Empty;

                if (PortHelper.IsOpen)
                {
                    PortHelper.DiscardInBuffer();
                    PortHelper.CloseCom(out msg);
                }

                RegisterButtonText = "打开";
                RegisterButtonColor = Brushes.LimeGreen;
            }
            catch (Exception ex)
            {
                AppendToLog(usbI2cLogTextBox, ex.Message.ToString());
            }
        }
    }
}
